﻿/*
    Copyright 2008 Travis Scholtens
    
    This file is part of Anticipa-Do List.

    Anticipa-Do List is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Anticipa-Do List is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with Anticipa-Do List.  If not, see <http://www.gnu.org/licenses/>.
*/
using System;
using System.Collections.Generic;
using System.Text;

using Anticipa_Do_List;

using Google.GData.AccessControl;
using Google.GData.Calendar;
using Google.GData.Client;
using Google.GData.Extensions;

namespace GoogleCalendarsNotifier
{
    public class GoogleCalendarsNotifier : INotificationManager
    {
        private CalendarService service = null;
        private CalendarEntry calendar = null;

        public string Description
        {
            get { return "Google Calendars Email Notification"; }
        }

        public List<KeyValuePair<string, bool>> GetConfigurationKeys()
        {
            var keys = new List<KeyValuePair<string, bool>>();
            keys.Add(new KeyValuePair<string, bool>("Username", false));
            keys.Add(new KeyValuePair<string, bool>("Password", true));
            keys.Add(new KeyValuePair<string, bool>("Calendar", false));
            return keys;
        }

        public void SetConfigurationValues(List<string> values)
        {
            var uri = new Uri("http://www.google.com/calendar/feeds/default/allcalendars/full");
            service = new CalendarService("tps12-AnticipaDoList-1");
            service.setUserCredentials(values[0], values[1]);

            var query = new CalendarQuery();
            query.Uri = uri;

            // retrieve calendar, creating if doesn't exist
            foreach(CalendarEntry entry in service.Query(query).Entries)
                if (entry.Title.Text == values[2])
                {
                    calendar = entry;
                    break;
                }
            if (calendar == null)
            {
                calendar = new CalendarEntry();
                calendar.Title.Text = values[2];
                calendar.TimeZone = string.Format("{0:yyyy-MM-dd HH:mm}",
                    System.TimeZone.CurrentTimeZone.GetUtcOffset(DateTime.Now));
                calendar = (CalendarEntry)service.Insert(uri, calendar);
            }
        }

        public void SetNotification(Guid id, string description, DateTime time)
        {
            if (calendar == null) return;

            // look for existing event
            string[] parts = calendar.Id.AbsoluteUri.Split('/');
            var events = service.Query(new EventQuery(string.Format(
                "http://www.google.com/calendar/feeds/{0}/private/full",
                parts[parts.Length - 1])));

            // find existing entry or create new
            EventEntry e = null;
            string idKey = "http://baseballn00b.blogspot.com/atd#id";
            foreach (EventEntry entry in events.Entries)
            {
                foreach (object item in entry.ExtensionElements)
                    if (item is ExtendedProperty)
                    {
                        var property = (ExtendedProperty)item;
                        if (property.Name == idKey && property.Value == id.ToString())
                        {
                            e = entry;
                            break;
                        }
                    }
                if (e != null)
                    break;
            }
            if (e == null)
            {
                e = new EventEntry(description);
                e.ExtensionElements.Add(new ExtendedProperty(id.ToString(), idKey));
                e = service.Insert(events, e) as EventEntry;
            }

            // clear any times and reminders and re-add
            e.Times.Clear();
            e.Times.Add(new When(time, time + new TimeSpan(1, 0, 0)));
            
            e.Reminders.Clear();
            var rem = new Reminder();
            rem.Hours = 1;
            rem.Method = Reminder.ReminderMethod.email;
            e.Reminders.Add(rem);

            e.Update();
        }
    }
}
